package sdk.webview.fmc.com.fmcsdk.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;


import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import sdk.webview.fmc.com.fmcsdk.BuildConfig;
import sdk.webview.fmc.com.fmcsdk.activity.CaptureActivity;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.LoginActivity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.bean.Auth;
import sdk.webview.fmc.com.fmcsdk.bean.User;
import sdk.webview.fmc.com.fmcsdk.db.DBManager;
import sdk.webview.fmc.com.fmcsdk.db.Record;

public class Utility {
    /**
     * @param scanResult 扫描的结果
     * @return
     */
    public static String getScanCode(String scanResult) {
        String code = "";
        try {
            if (scanResult.contains("id=")) {
                code = scanResult.substring(scanResult.indexOf("id=") + 3, scanResult.indexOf("&"));
            } else {
                code = scanResult;
            }
        } catch (Exception e) {
            e.printStackTrace();

            if (TextUtils.isEmpty(code)) {
                code = scanResult;
            }
        }
        return code;
    }

    public static int width = -1;

    /**
     * 安装apk
     *
     * @param apkFile
     * @param activity
     */
    public static void install(File apkFile, Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkFile),
                "application/vnd.android.package-archive");
        activity.startActivity(intent);
        activity.finish();
    }

    public static boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceName.equals(service.service.getClassName())) {
                isRunning = true;
            }
        }
        return isRunning;
    }

    public static SharedPreferences getMutiProcessSharedPrefs(Context context) {
        return context.getSharedPreferences("mutipro", Context.MODE_MULTI_PROCESS);
    }


    /**
     * 判断应用是否已经启动
     *
     * @param context     一个context
     * @param packageName 要判断应用的包名
     * @return boolean
     */
    public static boolean isAppAlive(Context context, String packageName) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos
                = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (processInfos.get(i).processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取手机串号IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
        if (targetSdkVersion > Build.VERSION_CODES.O && Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            return getUniqueID(context);
        } else {
            return getTelId(context);
        }

    }


    private static String getTelId(Context context) {
        try {
            final TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return manager.getDeviceId();
        } catch (Exception e) {
            return getUniqueID(context);
        }

    }

    private static String getUniqueID(Context context) {
        String id = null;
        final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(androidId) && !"9774d56d682e549c".equals(androidId)) {
            try {
                UUID uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                id = uuid.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        if (TextUtils.isEmpty(id)) {
            id = getUUID();
        }

        return TextUtils.isEmpty(id) ? UUID.randomUUID().toString() : id;
    }

    private static String getUUID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                ((null != Build.CPU_ABI) ? Build.CPU_ABI.length() : 0) % 10 +

                Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 +

                Build.HOST.length() % 10 + Build.ID.length() % 10 +

                Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10 +

                Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 +

                Build.TYPE.length() % 10 + Build.USER.length() % 10; //13 位

//		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = android.os.Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial" + UUID.randomUUID().toString(); // 随便一个初始化
        }
//		} else {
//			serial = android.os.Build.UNKNOWN + UUID.randomUUID().toString(); // 随便一个初始化
//		}

        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }


    /**
     * 获取手机id
     *
     * @param context
     * @return androidId
     */
    public static String getAndroidId(Context context) {
        return Secure.getString(context.getContentResolver(),
                Secure.ANDROID_ID);
    }

    /**
     * @return 手机序列号
     */
    public static String getSerialNumber() {
        return android.os.Build.SERIAL;
    }

    /**
     * 获取手机序列号，如果序列号为空，就取imei
     *
     * @param context
     * @return
     */
    public static String getSerialNumber(Context context) {
        String number = getSerialNumber();
        return TextUtils.isEmpty(number) ? getIMEI(context) : number;
    }

    /**
     * 获取屏幕参数DisplayMetrics
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }

    /**
     * dp转换成px
     *
     * @param context
     * @param dp
     * @return
     */
    public static final int dp2px(Context context, float dp) {
        return (int) (dp * getDisplayMetrics(context).density + 0.5f);
    }

    /**
     * px转dp
     *
     * @param context
     * @param px
     * @return
     */
    public static int px2dip(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }


    /**
     * sp转换成px
     *
     * @param context
     * @param sp
     * @return
     */
    public static final int sp2px(Context context, float sp) {
        return (int) (sp * getDisplayMetrics(context).scaledDensity + 0.5f);
    }


    /**
     * convert px to its equivalent sp
     * <p>
     * 将px转换为sp
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 获取Apk版本
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            return null;
        }
        return info.versionName;
    }

    /**
     * 获取Manifest中定义的metadata
     *
     * @param context
     * @param key
     * @return
     */
    public static Object getMetaData(Context context, String key) {
        try {
            ApplicationInfo appinfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return appinfo.metaData.get(key);
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    /**
     * 打电话
     *
     * @param context
     * @param phonenum
     */
    public static void dail(Context context, String phonenum) {
        Uri uri = Uri.parse("tel:" + phonenum);
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        context.startActivity(intent);
    }


    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    /**
     * 获取Activity堆栈中最顶部的Activity
     *
     * @param context
     * @return
     */
    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null)
            return runningTaskInfos.get(0).topActivity.getClassName();
        else
            return "";
    }

    public static Locale getLocale(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        return locale;
    }


    /**
     * 跳转到H5的首页
     */
    private static Intent gpsIntent;
    private static Intent uploadImageIntent;

    public static void startLoginActivityForH5Home(Context context) {
        XLog.i("startLoginActivityForH5Home");

//        boolean pushStopped = JPushInterface.isPushStopped(context.getApplicationContext());
//        if (!pushStopped) {
//            JPushInterface.stopPush(context);
//        }
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.H5_TITLE, "");
        intent.putExtra(Constant.HIDE_HEADER, false);
//		intent.putExtra(Constant.H5_URL, defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL,"")+"/fmc/h5/mytask/?accessToken=" + UserHelper.getToken());
        intent.putExtra(Constant.H5_URL, defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + "/h5/mytask/?accessToken=" + UserHelper.getToken());
        intent.setClass(context, H5Activity.class);
        context.startActivity(intent);

        FileUtil.deleteLogFiles(context);


    }

    /**
     * 跳转到登录界面并清除数据
     */
    public static void startLoginActivityOrClearData(Context context) {

        XLog.i("startLoginActivityOrClearData");
        //极光停止推送
//        JPushInterface.stopPush(context);
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        if (UserHelper.getSavedUser() != null) {
            defaultSharedPreferences.edit().putString(Constant.LAST_LOGIN_NAME, UserHelper.getSavedUser().getRecord().getLoginId()).apply();
        }
        defaultSharedPreferences.edit().putString(Constant.LAST_ADDRESS, defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "")).apply();
        //登录失败则跳转到登录页面
        defaultSharedPreferences.edit().putBoolean(Constant.ISLOGIN, false).apply();
//		PreferencesHelper.remove(SystemSetting.class);
        PreferencesHelper.remove(Auth.class);
        PreferencesHelper.remove(User.class);
        /**删除图片和图片缓存*/
        Utility.clearImageData(context);
        defaultSharedPreferences.edit().remove(Constant.FIRST_OPEN).apply();
        //清除开发人员调试H5的路径
        defaultSharedPreferences.edit().remove(Constant.H5_TEST).apply();

        context.startActivity(new Intent(context, LoginActivity.class));
        //删除头像
        FileUtil.deleteOneFile(ImageUtils.getImagePath(Constant.SRCAVATAR, context));

//		AppManager.getAppManager().finishActivity(H5Activity.class);
    }

    /**
     * 跳转到登录界面，不删除图片
     */
    public static void startLoginActivity(Context context) {

        XLog.i("startLoginActivity");
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
//        JPushInterface.stopPush(context);


//        AppManager.getAppManager().finishAllActivity();
        Intent intents = new Intent();
        intents.setClass(context, LoginActivity.class);
//        intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intents);
        PreferencesHelper.remove(User.class);
        defaultSharedPreferences.edit().remove(Constant.FIRST_OPEN).apply();
        //删除头像
        FileUtil.deleteOneFile(ImageUtils.getImagePath(Constant.SRCAVATAR, context));

    }


    /**
     * 删除H5离线拍摄上传成功之后相关的图片
     */
    public static void deleteH5Image(Context context, Record record) {
        DBManager.getDBManager(context).delete(record);
        File file = new File(ImageUtils.getH5ImagePath(record.getString("imageUrl"), context));
        if (file.exists()) {
            file.delete();//删除文件
        }
        File thfile = new File(ImageUtils.getH5ImageThumPath(record.getString("imageUrl"), context));
        if (thfile.exists()) {
            thfile.delete();//删除缩略图文件
        }
    }


    /**
     * 删除H5离线拍摄相关的图片
     */
    public static void deleteH5ImageNotUpload(String imageName, Context context) {

        File file = new File(ImageUtils.getH5ImagePath(imageName, context));
        if (file.exists()) {
            file.delete();//删除文件
        }
        File thfile = new File(ImageUtils.getH5ImageThumPath(imageName, context));
        if (thfile.exists()) {
            thfile.delete();//删除缩略图文件
        }
    }


    /**
     * 打开扫描界面
     *
     * @param activity
     * @param requestCode
     */
    public static void startScanActivity(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, CaptureActivity.class);
        intent.putExtra("bletooth", "0");
        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 调用系统相机拍照
     *
     * @param activity    当前activity
     * @param requestCode 请求
     * @param fileName    保存的文件名称
     * @param type        摄像头类型
     *                    Camera.CameraInfo.CAMERA_FACING_BACK 后置
     *                    Camera.CameraInfo.CAMERA_FACING_FRONT 后置
     */
    public static void startPhotoAcitivity(Activity activity, int requestCode, String fileName, int type) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("android.intent.extras.CAMERA_FACING", type);
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = activity.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");

        }
        File path = new File(storePath);
        if (!path.exists())
            path.mkdir();


        if (Build.VERSION.SDK_INT >= 23) {
            XLog.i("package:" + activity.getApplication().getPackageName());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(activity, activity.getApplication().getPackageName() + ".fileprovider", new File(ImageUtils.getImagePath(fileName, activity))));
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(ImageUtils.getImagePath(fileName, activity))));
        }

        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 调用系统相机拍照
     *
     * @param activity    当前activity
     * @param requestCode 请求
     * @param fileName    保存的文件名称
     * @param type        摄像头类型
     *                    Camera.CameraInfo.CAMERA_FACING_BACK 后置
     *                    Camera.CameraInfo.CAMERA_FACING_FRONT 后置
     */
    public static void startPhotoActivityForH5(Activity activity, int requestCode, String fileName, int type) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("android.intent.extras.CAMERA_FACING", type);

        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = activity.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");

        }

//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        File path = new File(storePath);
        if (!path.exists())
            path.mkdir();


        if (Build.VERSION.SDK_INT >= 23) {
            XLog.i("package:" + activity.getApplication().getPackageName());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(activity, activity.getApplication().getPackageName() + ".fileprovider", new File(fileName)));
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
        }

        activity.startActivityForResult(intent, requestCode);
    }


    public static void clearImageData(Context activity) {
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = activity.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");

        }
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        File file = new File(storePath + Constant.IMAGEPATH);
        if (file.exists()) {
            FileUtil.deleteFile(file);
        }
    }

    public static void clearH5ImageData(Context activity) {
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = activity.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(activity).getString(Constant.APP_NAME, "fmsdk");

        }
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        File file = new File(storePath + Constant.H5IMAGEPATH);
        if (file.exists()) {
            FileUtil.deleteFile(file);
        }
    }


    public static void startPhotoActivity(Activity activity, int requestCode, String fileName) {
        startPhotoAcitivity(activity, requestCode, fileName, Camera.CameraInfo.CAMERA_FACING_BACK);
    }

    public static void startPhotoActivityForH5(Activity activity, int requestCode, String fileName) {
        startPhotoActivityForH5(activity, requestCode, fileName, Camera.CameraInfo.CAMERA_FACING_BACK);
    }


    //判断GPS是否开启
    public static boolean gpsIsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }


    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
